﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using TVersityDotNet.HelperTypes;
using System.Collections.ObjectModel;
using System;
using System.Globalization;

namespace TVersityDotNet.Responses
{
    public class MediaSourceFetchListResponse : TVersityResponse
    {
        public Collection<MediaSource> ListOfSources { get; private set; }

        public MediaSourceFetchListResponse(XDocument responseXmlDoc)
        {
            this.ListOfSources = new Collection<MediaSource>();
            this.ParseMessage(responseXmlDoc);            
        }

        public override void ParseMessage(XDocument responseXml)
        {
            if (responseXml != null)
            {
                base.ParseMessage(responseXml);

                var query = from result in responseXml.Descendants("result")
                            where result.Attribute("is_public") == null
                            select new MediaSource                            
                            {
                                Id = int.Parse(result.Attribute("id").Value, CultureInfo.InvariantCulture),
                                Name = result.Attribute("name").Value,
                                Url = result.Attribute("url").Value,
                                Tags = new Collection<string>(result.Attribute("tags").Value.Split(new char[] { ',' })),
                                MSType = MediaSource.GetMediaTypeByName(result.Attribute("type").Value),
                                Public = true
                            };

                foreach (MediaSource mediaSource in query)
                {
                    this.ListOfSources.Add(mediaSource);
                }

                var query2 = from result in responseXml.Descendants("result")
                            where result.Attribute("is_public") != null
                            select new MediaSource
                            {
                                Id = int.Parse(result.Attribute("id").Value, CultureInfo.InvariantCulture),
                                Name = result.Attribute("name").Value,
                                Url = result.Attribute("url").Value,
                                Tags = new Collection<string>(result.Attribute("tags").Value.Split(new char[] { ',' })),
                                MSType = MediaSource.GetMediaTypeByName(result.Attribute("type").Value),
                                Public = bool.Parse(result.Attribute("is_public").Value)
                            };

                foreach (MediaSource mediaSource in query2)
                {
                    this.ListOfSources.Add(mediaSource);
                }
            }
            else
            {
                this.ResponseSuccess = false;
                this.ResponseMessage = "Provided responseXml was null";
            }
        }
    }
}
